//指定正常商品
function designatedCommodity() {
    $(".dataTables_wrapper").css({
        display: "inline"
    });
    $.ajax({
        url:root.member.productAppointRulelistPage,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            pageNum:1,
            pageSize:20,
            "mainCustomerId" :mainCustomerIds,
            "spuCode":$("#spuCode").val(),
            "spuName":$("#spuName").val()

        }),
        success: function (result) {
            designatedCommoditylist(result);
            $('.M-box3').pagination({
                pageCount: result.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.member.productAppointRulelistPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            pageNum:api.getCurrent(),
                            pageSize:20,
                            "mainCustomerId" :mainCustomerIds,
                            "spuCode":$("#spuCode").val(),
                            "spuName":$("#spuName").val()

                        }),
                        success: function (result) {
                            designatedCommoditylist(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
/*表格渲染*/
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];

function designatedCommoditylist(data) {
    console.log(data)
    dataSource.splice(0, dataSource.length);//清空数组
    if (data.data.data!="") {
        $.each(data.data.data, function (i, field) {
            var rowData = new Array();
            rowData.push(field.spuCode);
            rowData.push(field.spuName);
            rowData.push(field.operateUserName);
            rowData.push(field.updateTime);
            rowData.push(field.productAppointRuleId);
            dataSource.push(rowData);
        });
    }
    initDataTable(dataSource);

    function initDataTable(dataSource) {
        var dttable = $('#designateddatatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#designateddatatable").DataTable({
            "order": [[ 1, "desc" ]],
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span style="text-align: left;"><td><input class="spuId" type="checkbox" name="spuId" data-code="'+row[0]+'" data-name="'+row[1]+'" value = "' + row[4] + '">' + row[0] + '</td></span>';
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },

                {
                    "render": function (data, type, row) {
                        var val = '<span class=""><a onclick="detaildelete(\''+row[4]+'\',\''+row[0]+'\',\''+row[1]+'\')">移除</a></span>';
                        return val;
                    },
                    "targets": 4
                }
            ],
            "fnInitComplete": function(oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function() {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });

            }
        });
    };
    //权限控制函数
    power()
}

//单个删除
function detaildelete(id,code,name) {

    var productAppointRuleDtos={}
    var productAppointRuleDtosarr = [];
    productAppointRuleDtos={
        productAppointRuleId:id,
        spuCode:code,
        spuName:name
    }
    productAppointRuleDtosarr.push(productAppointRuleDtos);
    $.ajax({
        url:root.member.productAppointRuledeleteBatchByIds,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({
            "operateUserId":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "mainCustomerId":mainCustomerIds,
            "productAppointRuleDtos":productAppointRuleDtosarr
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('移除成功！',2000);
                designatedCommodity();
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}
//批量删除
function batchdelete() {

    var productAppointRuleDtos={}
    var productAppointRuleDtosarr = [];
    var spuIdArr=document.getElementsByName('spuId');
    for(var i=0; i < spuIdArr.length;i++){
        if(spuIdArr[i].checked==true){
            productAppointRuleDtos={
                productAppointRuleId:spuIdArr[i].value,
                spuCode:$(spuIdArr[i]).attr("data-code"),
                spuName:$(spuIdArr[i]).attr("data-name")
            }
            productAppointRuleDtosarr.push(productAppointRuleDtos)
        }

    }
    if(productAppointRuleDtosarr==''){
        $.Huimodalalert('请选择批量选择数据！',2000);
        return false;
    }
    $.ajax({
        url:root.member.productAppointRuledeleteBatchByIds,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({
            "operateUserId":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "mainCustomerId":mainCustomerIds,
            "productAppointRuleDtos":productAppointRuleDtosarr
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('移除成功！',2000);
                $("#spu_all1").attr("checked",false);
                designatedCommodity();
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })

}
//导入
function batchAdding() {
    $("#batchAdding").trigger('click');
}
//批量新增
function batchAddingports() {
    var name=$("#batchAdding").val()
    var result = /\.[^\.]+/.exec(name);
    /* if (result != ".xlsx" && result != ".xls") {
         $.Huimodalalert('格式不正确！',2000);
         return false;
     }*/
    var formData = new FormData();
    formData.append('mainCustomerId', mainCustomerIds);
    formData.append('file', $("#batchAdding")[0].files[0]);
    formData.append('operateUserId', JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID);
    formData.append('operateUserName', JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name);
    $.ajax({
        url: root.member.productAppointRuleimportAppointRuleExcel,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            $('#batchAdding').val('');
            $("#batchAdding").attr('type','file');
            if(data.errorCode==0){
                $.Huimodalalert('导入成功'+data.data.success_num+'条，失败'+data.data.error_num+'条',2000);
                designatedCommodity()

            }else {
                $.Huimodalalert(data.msg,2000);
            }

        }
    });
}
//下载模板
function downloadTemplate() {
    $("#downloadTemplate").attr("href",root.orderInter.downLoadFromUrl +'?urlStr=https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20200919154311721884.xlsx&fileName=指定商品导入模板')

}
//下载错误值
function downloaderrorvalue() {
    $('#downloaderrorvalue').attr('href',root.member.productAppointRuleexport+"?moduleType=10&operateUserId="+JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID)

}

